package org.uned.agonzalo16.bitacora.web.search;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.uned.agonzalo16.bitacora.domain.Article;
import org.uned.agonzalo16.bitacora.domain.Blog;
import org.uned.agonzalo16.bitacora.service.search.SearchService;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
import org.uned.agonzalo16.bitacora.service.security.AuthenticationProvider;

@RequestMapping("/search")
@Controller
public class SearchController {

	@Autowired
	private SearchService searchService;

	@Autowired
	private AuthenticationProvider authenticationProvider;

	@RequestMapping(method = RequestMethod.GET, value = "/doSearch")
	public String doSearch(@RequestParam("query") String query, Model model) {

		List<Article> articles = searchService.searchArticles(query);
		List<Blog> blogs = searchService.searchBlogs(query);
		model.addAttribute("articles", articles);
		model.addAttribute("blogs", blogs);
		model.addAttribute("query", query);

		AuthenticatedUser user = authenticationProvider.getCurrentUserDetails();

		if (user == null) {
			return "search";
		} else {
			return "registerSearch";
		}
	}
}
